<?php

/**
 * subscriber actions.
 *
 * @package    sf_sandbox
 * @subpackage subscriber
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2288 2006-10-02 15:22:13Z fabien $
 */
class subscriberActions extends autosubscriberActions
{

    /**
    * Displays form for users to subscribe for newsletter. Template - 'indexSuccess.php'.
    * After submition forwards to action 'validateSubscribe'.
    */
    public function executeIndex()
    {
    
    }


    /**
    * Creates new Subscribers object and sets its e-mail field from request from previous action 'ValidateSubscribe'.
    * Saves the object to the database.
    * Sends email to the provided recipient with confirmation link
    * Displays successful subscribtion message.
    */
    public function executeSubscribe()
    {
    	if( $this->getRequest()->getMethod() == sfRequest::POST )
        {
	        sfLoader::loadHelpers('Partial');
	        //debugvar($this->getRequestParameter('email'), 'mail');
	        $subscriber = new Subscriber();
	        $subscriber->setUserId(get_user_id());
	        $subscriber->setLng($this->getUser()->getCulture());
	        $subscriber->setStatusId(MyConstants::STATUS_NEW);
	        //$subscriber->setUid($uid->getUid());
	        $subscriber->setEmail($this->getRequestParameter('email'));
	        $subscriber->setTags('1');
	
	        $subscriber->save();
	        
	        $uid = Uid::createNew($subscriber->getId(), MyConstants::TYPE_SUBSCRIBER);
	        
	        $body = get_partial('subscriber/subscribtion_mail'
	                            , array('uid' => $uid->getUid()));
	        $subject = __('News subscription confirmation');
	        News::sendMail(sfConfig::get('app_webmaster_mail')
	                    , sfConfig::get('app_webmaster')
	                    , $this->getRequestParameter('email')
	                    , $subject
	                    , $body);
	
	        $this->setFlash('subscribeSuccess', 'Your request was sent. Please check your mailbox for confirmation e-mail.');
        }
        return $this->forward('subscriber', 'index');
    }

    /**
    * Gets subscriber object from database by request parameter 'email' from previous action 'validateUnsubscribe'. Sets its status to 'PendingDelete', saves to database and sends confirmation email.
    */
    public function executeRemove()
    {
        $c = new Criteria();
        $c->add(SubscriberPeer::EMAIL, $this->getRequestParameter('email'));
        $c->add(SubscriberPeer::STATUS_ID, MyConstants::STATUS_DELETED, Criteria::NOT_EQUAL);
        $result = SubscriberPeer::doSelectOne($c);

        $result->setStatusId(MyConstants::STATUS_PENDING_DELETE);
        $result->save();
        
        $uid = Uid::createNew($result->getId(), MyConstants::TYPE_SUBSCRIBER, ( 326 * 24 * 60 * 60));
        
        sfLoader::loadHelpers('Partial');
        $body = get_partial('subscriber/remove_mail'
                            , array('uid' => $uid->getUid()));
        $subject = __('News unsubscribe confirmation');
        News::sendMail(sfConfig::get('app_webmaster_mail')
                    , sfConfig::get('app_webmaster')
                    , $this->getRequestParameter('email')
                    , $subject
                    , $body);

        $this->setFlash('unsubscribeSuccess', 'You unsubscribed our newsletter. Please check your mailbox for confirmation e-mail.');
        return $this->forward('subscriber', 'unsubscribe');
    }

    /**
    * Gets e-mail address from request from previous action 'executeIndex' and check if it is already in the database and what is its status. If it's not in the database or if it's status 'Deleted', forwards to second action 'executeSubscribe'. If its status 'New', 'Aproved' or 'PendingDelete', returns error.
    */
    public function validateSubscribe()
    {
        $isOk = true;
        $c = new Criteria();
        $c->add(SubscriberPeer::EMAIL, $this->getRequestParameter('email'));
        $c->add(SubscriberPeer::STATUS_ID, MyConstants::STATUS_DELETED, Criteria::NOT_EQUAL);
        $result = SubscriberPeer::doSelectOne($c);

        if ($result)
        {
        	if ($result->getStatusId() == MyConstants::STATUS_NEW)
        	{
        		$this->getRequest()->setError('email', 'You have already applied for subscribtion. Please check your mailbox for confirmation e-mail.');
                $isOk = false;
        	}
            elseif ($result->getStatusId() == MyConstants::STATUS_APPROVED)
            {
                $this->getRequest()->setError('email', 'This e-mail is already in subscribers list.');
                $isOk = false;
            }
            elseif ($result->getStatusId() == MyConstants::STATUS_PENDING_DELETE)
            {
                $this->getRequest()->setError('email', 'You aplied for unsubscribtion but have not confirmed it yet.');
                $isOk = false;
            }
        }
        else
            $isOk = true;

        return $isOk;
    }

    /**
    * Gets e-mail address from request and check if it is already in the database and what is its status. If it's not in the database or if it's status 'New' 'PendingDelete' or 'Deleted', returns error. If its status 'Aproved' forwards to second action 'executeRemove'.
    */
    public function validateRemove()
    {
        $isOk = true;

        $c = new Criteria();
        $c->add(SubscriberPeer::EMAIL, $this->getRequestParameter('email'));
        $c->add(SubscriberPeer::STATUS_ID, MyConstants::STATUS_DELETED, Criteria::NOT_EQUAL);
        $result = SubscriberPeer::doSelectOne($c);

        if ($result)
        {
            if($result->getStatusId() == MyConstants::STATUS_NEW)
            {
            	$this->getRequest()->setError('email', 'You have applied for our newsletter subscribtion but never confirmed it. Please check your mailbox for confirmation e-mail.');
                $isOk = false;
            }
            elseif($result->getStatusId() == MyConstants::STATUS_APPROVED)
            {
                $isOk = true;
            }
            elseif ($result->getStatusId() == MyConstants::STATUS_PENDING_DELETE)
            {
                $this->getRequest()->setError('email', 'You have already applied for unsubscribtion. Please check your mailbox for confirmation e-mail.');
                $isOk = false;
            }
        }
        else
        {
            $this->getRequest()->setError('email', 'This e-mail is not in our subscribers list.');
            $isOk = false;
        }
        return $isOk;
    }

    public function handleErrorSubscribe()
    {
        $this->forward('subscriber', 'index');
    }

    public function handleErrorRemove()
    {
        $this->forward('subscriber', 'unsubscribe');
    }

    /**
    * Checks if unique id from url exists in database and what its object status. If it is not in teh database or if its status 'Aproved', 'PendingDelete' or 'Deleted', returns error. If it is 'New', changes status to 'Aproved', saves and shows success message to the user.
    */
    public function executeConfirm()
    {
    	/* @var $uid Uid */
    	try {
    	   $uid = Uid::getAndValidateUid($this->getRequestParameter('uid'));
    	   $uid->setStatusId(MyConstants::STATUS_USED);
    	   $uid->save();
    	   $subscriber = SubscriberPeer::retrieveByPK($uid->getObjId());
    	   if($subscriber)
    	   {
    	       $subscriber->setStatusId(MyConstants::STATUS_APPROVED);
    	       $subscriber->save();
    	       $this->message = 'Confirmation success. Your e-maill is registered.';
    	   }else 
    	   {
    	       $this->setFlash('exceptionError', 'Something is wrong, your email not found,  please contact the web administrator.');
               $this->redirect('subscriber/error');
    	   }
        }catch ( exceptionNotFound $e )
        {
        	$this->setFlash('exceptionError', 'Unique id is not found, please try subscribe again.');
        	$this->redirect('subscriber/error');
        }catch ( exceptionUnexceptedStatus  $e )
        {
            $this->setFlash('exceptionError', 'Unique id is not valid, please try subscribe again.');
            $this->redirect('subscriber/error');
        }catch ( exceptionAlreadyUsed  $e )
        {
            $this->setFlash('exceptionError', 'Unique id is used and not valid.');
            $this->redirect('subscriber/error');
        }catch ( exceptionTimeOut  $e )
        {
            $uid = Uid::getByUidIdType($this->getRequestParameter('uid')
                                    , MyConstants::TYPE_SUBSCRIBER);
            if($uid->getStatusId())
            {
                $uid->setStatusId(MyConstants::STATUS_DELETED);
                $uid->save();
                $subscriber = SubscriberPeer::retrieveByPK($uid->getObjId());
                if($subscriber)
                {
                    /* @var $subscriber Subscriber */
                    $subscriber->setStatusId(MyConstants::STATUS_DELETED);
                    $subscriber->save();
                }
            }
            $this->setFlash('exceptionError', 'Unique id is not valid, time out. Try subscribe again.');
            $this->redirect('subscriber/error');
        }
    }


    public function executeError()
    {
    	
    }
    /**
    * Checks if unique id from url exists in database and what its object status. If it is not in teh database or if its status 'New', 'Aproved' or 'Deleted', returns error. If it is 'PendingDelete', changes status to 'Deleted', saves and shows success message to the user.
    */
    public function executeConfirmremove()
    {
    /* @var $uid Uid */
        try {
           $uid = Uid::getAndValidateUid($this->getRequestParameter('uid'));
           $uid->setStatusId(MyConstants::STATUS_USED);
           $uid->save();
           $subscriber = SubscriberPeer::retrieveByPK($uid->getObjId());
           if($subscriber)
           {
               $subscriber->setStatusId(MyConstants::STATUS_DELETED);
               $subscriber->save();
               $this->message = 'Confirmation success. Your e-maill is unregistered.';
           }else 
           {
               $this->setFlash('exceptionError', 'Something is wrong, your email not found,  please contact the web administrator.');
               $this->redirect('subscriber/error');
           }
        }catch ( exceptionNotFound $e )
        {
            $this->setFlash('exceptionError', 'Unique id is not found, please try subscribe again.');
            $this->redirect('subscriber/error');
        }catch ( exceptionUnexceptedStatus  $e )
        {
            $this->setFlash('exceptionError', 'Unique id is not valid, please try subscribe again.');
            $this->redirect('subscriber/error');
        }catch ( exceptionAlreadyUsed  $e )
        {
            $this->setFlash('exceptionError', 'Unique id is used and not valid.');
            $this->redirect('subscriber/error');
        }catch ( exceptionTimeOut  $e )
        {
            $uid = Uid::getByUidIdType($this->getRequestParameter('uid')
                                       , MyConstants::TYPE_SUBSCRIBER);
            if($uid->getStatusId())
            {
                $uid->setStatusId(MyConstants::STATUS_USED);
                $uid->save();
                $subscriber = SubscriberPeer::retrieveByPK($uid->getObjId());
                if($subscriber)
                {
                    $subscriber->setStatusId(MyConstants::STATUS_APPROVED);
                    $subscriber->save();
                }
            }
            $this->setFlash('exceptionError', 'Unique id is not valid, time out, pleace try agen to unsubscribe.');
            $this->redirect('subscriber/error');
        }
    }

    /**
    * Displays form for user to unsubscribe from newsletter. After submition forwards to action 'validateRemove'
    */
    public function executeUnsubscribe()
    {

    }
    

    /**
    * Get subscriber id from request, changes its status to 'Deleted', saves to database and forwards to subscribers list.
    */
    public function executeSuspend()
    {
        $subscriber = SubscriberPeer::RetrieveByPk($this->getRequestParameter('id'));
        $subscriber->setStatusId(MyConstants::STATUS_DELETED);
        $subscriber->save();
        return $this->redirect('subscriber/list');
    }

    /**
    * Get subscriber id from request, changes its status to 'Aproved', saves to database and forwards to subscribers list.
    */
    public function executeAprove()
    {
        $subscriber = SubscriberPeer::RetrieveByPk($this->getRequestParameter('id'));
        $subscriber->setStatusId(MyConstants::STATUS_APPROVED);
        $subscriber->save();
        return $this->redirect('subscriber/list');
    }
}